<template>
	<el-card shadow="hover">
		<el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
			<el-form-item label="商品编号" prop="goods_id">
				<el-input v-model="queryParams.goods_id" placeholder="商品编号" clearable />
			</el-form-item>
			<el-form-item label="商品名称" prop="title">
				<el-input v-model="queryParams.title" placeholder="商品名称" clearable />
			</el-form-item>
			<el-form-item label="商品分类" prop="goods_class_id">
				<el-cascader v-model="queryParams.goods_class_id" :props="goodsClassProps" placeholder="请选择商品分类" />
			</el-form-item>
			<el-form-item label="商品状态" prop="status">
				<el-select v-model="queryParams.status">
					<el-option label="全部" value="" />
					<el-option label="启用" value="1" />
					<el-option label="禁用" value="2" />
				</el-select>
			</el-form-item>
			<el-form-item label="销售情况" prop="sale">
				<el-select v-model="queryParams.sale">
					<el-option label="全部" value="" />
					<el-option label="即将售罄【小于10】" value="1" />
					<el-option label="子规格即将售罄" value="2" />
				</el-select>
			</el-form-item>
			<el-form-item label="即将上架" prop="grounding">
				<el-select v-model="queryParams.grounding">
					<el-option label="全部" value="" />
					<el-option label="5分钟内" value="5" />
					<el-option label="10分钟内" value="10" />
					<el-option label="20分钟内" value="20" />
					<el-option label="30分钟内" value="30" />
				</el-select>
			</el-form-item>
			<!-- <el-form-item label="专区商品" prop="is_zone">
				<el-select v-model="queryParams.is_zone">
					<el-option label="全部" value="" />
					<el-option label="是" value="1" />
					<el-option label="否" value="0" />
				</el-select>
			</el-form-item> -->
			<el-form-item label="商品标签" prop="tags_ids">
				<el-select v-model="queryParams.tags_ids" multiple collapse-tags collapse-tags-tooltip placeholder="请选择商品标签">
					<el-option v-for="item in goodsTagsOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="上架开始时间" prop="start_time">
				<el-date-picker v-model="queryParams.start_time" type="datetime" clearable value-format="X" placeholder="请选择开始时间" />
			</el-form-item>
			<el-form-item label="上架结束时间" prop="end_time">
				<el-date-picker v-model="queryParams.end_time" type="datetime" clearable value-format="X" placeholder="请选择结束时间" />
			</el-form-item>
			<el-form-item label="供应商" prop="supplier_id">
				<el-select
					v-model="queryParams.supplier_id"
					filterable
					remote
					clearable
					placeholder="请输入选择供应商"
					:remote-method="supplierIdRemoteMethod"
					:loading="supplierIdLoading"
					@focus="onSupplierIdFocus"
					@clear="onSupplierIdClear"
				>
					<el-option v-for="item in supplierIdOptions" :key="item.id" :label="item.title" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="onQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="onResetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="top-block mt8 mb8">
			<el-col :span="1.5">
				<el-button @click="onGoodAdd" type="primary" plain icon="el-icon-plus">添加</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button @click="onGoodExport" type="warning" plain icon="el-icon-download">导出</el-button>
			</el-col>
			<!-- <el-col :span="1.5">
				<el-button @click="onImportGoods" type="primary" plain icon="el-icon-upload2">导入商品</el-button>
			</el-col> -->
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
		</el-row>
		<el-table :data="tableList" v-loading="loading">
			<el-table-column label="商品编号" align="center" prop="id" />
			<el-table-column label="商品名" align="center" prop="title" />
			<el-table-column label="商品封面图" align="center">
				<template #default="scope">
					<el-image :src="scope.row.thumb" fit="scale-down" style="width: 60px; height: 60px" />
				</template>
			</el-table-column>
			<el-table-column label="上架时间" align="center">
				<template #default="scope">{{ timeDictionary(scope.row.start_time) }}</template>
			</el-table-column>
			<el-table-column label="下架时间" align="center">
				<template #default="scope">{{ timeDictionary(scope.row.end_time) }}</template>
			</el-table-column>
			<el-table-column label="分类" align="center" prop="goods_class_name" />
			<el-table-column label="供应商" align="center" prop="supplier_name" />
			<el-table-column label="原价" align="center" prop="old_price" />
			<el-table-column label="售价" align="center" prop="sale_price" />
			<el-table-column label="总库存" align="center" prop="stock" />
			<el-table-column label="虚拟销量" align="center" prop="virtual_sales" />
			<el-table-column label="真实销量" align="center" prop="real_sales" />
			<el-table-column label="状态" align="center">
				<template #default="scope">
					<el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="onStatus(scope.row)" />
				</template>
			</el-table-column>
			<el-table-column label="录入时间" align="center">
				<template #default="scope">{{ timeDictionary(scope.row.create_time) }}</template>
			</el-table-column>
			<el-table-column label="操作" align="center" fixed="right">
				<template #default="{ row }">
					<el-button @click="onGoodView(row)" type="text">查看</el-button>
					<el-button @click="onGoodEdit(row)" type="text">修改</el-button>
					<el-button @click="onGoodSkuEdit(row)" type="text">修改库存</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination-component
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>
		<good-add-dialog ref="goodAddRef" />
		<good-edit-dialog ref="goodEditRef" />
		<good-stock-view-dialog ref="goodStockViewRef" />
		<good-view-dialog ref="goodViewRef" />
		<good-import-dialog ref="goodImportRef" />
	</el-card>
</template>

<script lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { goodsDisableEnable, goodsList, goodsSelectClass, goodsSelectSupplier, goodsExport, goodsTagsList } from '/@/api/admin1';
import { endTimePlus, timeDictionary } from '/@/utils/dictionaryTranslation';
import { handleDownloadByName } from '/@/utils/utils';

import GoodAddDialog from './dialog/GoodAddDialog.vue';
import GoodEditDialog from './dialog/GoodEditDialog.vue';
import GoodStockViewDialog from './dialog/GoodStockViewDialog.vue';
import GoodViewDialog from './dialog/GoodViewDialog.vue';
import GoodImportDialog from './dialog/GoodImportDialog.vue';

export default {
	name: 'goodGood',
	components: { GoodAddDialog, GoodEditDialog, GoodStockViewDialog, GoodViewDialog, GoodImportDialog },
	setup() {
		const queryFormRef = ref(null);
		const generalRef = ref(null);
		const goodAddRef = ref(null);
		const goodEditRef = ref(null);
		const goodStockViewRef = ref(null);
		const goodViewRef = ref(null);
		const loadingExportRef = ref(null);
		const goodImportRef = ref(null);
		const state = reactive({
			single: true, // 非单个禁用
			multiple: true, // 非多个禁用
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				title: '',
				goods_id: '',
				goods_class_id: '',
				supplier_id: '',
				status: '',
				sale: '',
				grounding: '',
				start_time: '',
				end_time: '',
				// is_zone: '',
				tags_ids: [],
			},
			goodsClassProps: {
				lazy: true,
				lazyLoad(node: any, resolve: any) {
					const { value, level } = node;
					_goodsSelectClass({ pid: level ? value : 0, pageNum: 1, pageSize: 100 }, level, resolve);
				},
				value: 'id',
				label: 'name',
			},
			supplierIdLoading: false,
			supplierIdOptions: [] as any,
			goodsTagsOptions: [] as any,
			showSearch: true,
			tableList: [],
			loading: false,
			total: 0,
		});

		onMounted(() => {
			getList();
			_goodsTagsList({ pageNum: 1, pageSize: 100 });
		});

		/********** 点击事件(on开头) **********/
		// 选择供应商
		const onSupplierIdFocus = () => {
			if (!state.queryParams.supplier_id) {
				state.supplierIdLoading = true;
				_goodsSelectSupplier();
			}
		};
		// 清空供应商
		const onSupplierIdClear = () => {
			_goodsSelectSupplier();
		};
		// 搜索
		const onQuery = () => {
			state.queryParams.pageNum = 1;
			getList();
		};
		// 重置
		const onResetQuery = () => {
			(queryFormRef.value as any)?.resetFields();
			onQuery();
		};
		// 添加商品
		const onGoodAdd = () => {
			(goodAddRef.value as any)?.openDialog({}, () => getList());
		};
		// 编辑商品
		const onGoodEdit = (row: any) => {
			(goodEditRef.value as any)?.openDialog({ data: { goods_id: row.id } }, () => getList());
		};
		// 编辑商品库存
		const onGoodSkuEdit = (row: any) => {
			(goodStockViewRef.value as any)?.openDialog({ title: row.title, data: { goods_id: row.id } }, () => getList());
		};
		// 查看商品
		const onGoodView = (row: any) => {
			(goodViewRef.value as any)?.openDialog({ data: { goods_id: row.id } });
		};
		// 导出商品
		const onGoodExport = () => {
			(loadingExportRef.value as any) = ElLoading.service({
				lock: true,
				text: '正在导出，请耐心等待...',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			_goodsExport({
				...state.queryParams,
				tags_id: state.queryParams.tags_ids.join(','),
				goods_class_id: state.queryParams.goods_class_id[1],
				end_time: endTimePlus(state.queryParams.start_time, state.queryParams.end_time),
			});
		};
		// 导入商品
		const onImportGoods = () => {
			(goodImportRef.value as any)?.openDialog({}, () => getList());
		};
		// 启用、禁用
		const onStatus = (row: any) => {
			ElMessageBox.confirm(`是否确认${Number(row.status) == 1 ? '启用' : '禁用'}商品编号为${row.id}的数据项？`, '提示', { type: 'warning' })
				.then(() => {
					return _goodsDisableEnable({ status: row.status, goods_id: row.id });
				})
				.then(() => {
					ElMessage.success(`${Number(row.status) == 1 ? '启用' : '禁用'}成功`);
				})
				.catch(() => {
					row.status = row.status ? 0 : 1;
				});
		};

		/********** 方法事件 **********/
		const getList = () => {
			state.loading = true;
			_goodsList({
				...state.queryParams,
				tags_id: state.queryParams.tags_ids.join(','),
				goods_class_id: state.queryParams.goods_class_id[1],
				end_time: endTimePlus(state.queryParams.start_time, state.queryParams.end_time),
			});
		};
		//搜索供应商
		const supplierIdRemoteMethod = (query: string) => {
			if (query) {
				state.supplierIdLoading = true;
				_goodsSelectSupplier({ title: query });
			} else {
				return true;
			}
		};

		/********** 网络事件 **********/
		// 选择标签
		const _goodsTagsList = (_data: object) => {
			goodsTagsList(_data).then((res: any) => {
				console.log('选择标签', res);
				state.goodsTagsOptions = res.data.list;
			});
		};
		// 选择商品分类
		const _goodsSelectClass = (_data: object, _level: number, resolve: any) => {
			goodsSelectClass(_data).then((res: any) => {
				let nodes = res.data.list.map((item: any) => ({
					id: item.id,
					name: item.name,
					leaf: _level >= 1,
				}));
				resolve(nodes);
			});
		};
		// 选择供应商
		const _goodsSelectSupplier = (_data: object = {}) => {
			goodsSelectSupplier(_data)
				.then((res: any) => {
					state.supplierIdOptions = res.data.list;
					state.supplierIdLoading = false;
				})
				.catch(() => {
					state.supplierIdLoading = false;
				});
		};
		// 商品列表
		const _goodsList = (_data: object) => {
			goodsList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 导出商品
		const _goodsExport = (_data: object) => {
			goodsExport(_data)
				.then((res: any) => {
					handleDownloadByName(res.data.info.url, '商品导出', false);
					(loadingExportRef.value as any)?.close();
				})
				.catch(() => {
					(loadingExportRef.value as any)?.close();
				});
		};
		// 禁用和启用商品
		const _goodsDisableEnable = (_data: object) => {
			return goodsDisableEnable(_data);
		};

		return {
			queryFormRef,
			generalRef,
			goodAddRef,
			goodEditRef,
			goodStockViewRef,
			goodViewRef,
			loadingExportRef,
			goodImportRef,
			onSupplierIdFocus,
			onSupplierIdClear,
			onQuery,
			onResetQuery,
			onGoodAdd,
			onGoodExport,
			onImportGoods,
			onGoodEdit,
			onGoodSkuEdit,
			onGoodView,
			onStatus,
			getList,
			supplierIdRemoteMethod,
			timeDictionary,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped></style>
